package dao.jpa;

import dao.AlunoDAO;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import modelo.Aluno;
import modelo.Turma;
import util.JPAUtil;

/**
 *
 * @author Jorge
 */
public class AlunoJpaDAO extends AbstractJpaDao<Aluno, Long> implements AlunoDAO {

    public AlunoJpaDAO() {
        super(Aluno.class);
    }

    @Override
    public List<Aluno> getAll() {
        return JPAUtil.getEntityManager().createQuery("from Aluno").getResultList();
    }

    @Override
    public List<Aluno> getPorNome(String nome) {
        String s = "select a from Aluno a where upper(a.nome) like upper(?)";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, "%" + nome + "%");

        return (List<Aluno>) query.getResultList();
    }

    @Override
    public Aluno getPorIdComListaAlunoTurmas(Long id) {
        String s = "select a from Aluno a " +
                   "left outer join fetch a.listaAlunoTurma at " +
                   "where a.id=?";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, id);

        return (Aluno) query.getSingleResult();
    }

    @Override
    public Aluno getPorId(Long id) {
        String s = "select a from Aluno a where a.id=?";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, id);
        
        try {
            return (Aluno) query.getSingleResult();
        }
        catch(NoResultException e) {
            return null;
        }
    }

    @Override
    public List<Aluno> getDisponiveisPorTurma(Turma turmaCorrente) {
        String s = "select a from Aluno a where a not in " +
                "(select at.aluno from AlunoTurma at where at.turma=?)";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, turmaCorrente);

        return (List<Aluno>) query.getResultList();
    }
}
